package com.example.demo.controller;

import com.example.demo.common.AjaxResult;
import com.example.demo.common.UserSessionUtils;
import com.example.demo.entity.UserInfo;
import com.example.demo.entity.vo.CommentVO;
import com.example.demo.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created with IntelliJ IDEA 2023.
 * Description:
 * User: 故我
 * Date: 2023-11-26
 * Time: 20:36
 */
@RestController
@RequestMapping("/com")
public class CommentController {
    @Autowired
    private CommentService commentService;

    @RequestMapping("/addcom")
    public AjaxResult AddComment(HttpServletRequest request, Integer aid, String content) {
        // 先判断该用户是否是一个登录状态
        UserInfo userInfo = UserSessionUtils.getUser(request);
        if (userInfo == null) {
            return AjaxResult.fail(-1, "该用户未登录!");
        }
        // 参数的非空校验
        if (aid == null || content == null) {
            return AjaxResult.fail(-2, "非法参数!");
        }
        //从请求报头中获取ip
        String ip = request.getRemoteAddr();
        if(ip.equals("0:0:0:0:0:0:0:1")){
            ip = "127.0.0.1";
        }
        CommentVO commentVO = new CommentVO();
        if (userInfo.getNickname() == null) {
            commentVO.setNickname(userInfo.getUsername());
        } else {
            commentVO.setNickname(userInfo.getNickname());
        }
        commentVO.setAid(aid);
        commentVO.setContent(content);
        commentVO.setUid(userInfo.getId());
        commentVO.setIp(ip);
        return AjaxResult.success(commentService.AddComment(commentVO));
    }

    @RequestMapping("/allcom")
    public AjaxResult getAllComment(Integer aid) {
        // 判断非空参数
        if (aid == null) {
            return AjaxResult.fail(-1, "非法参数！");
        }
        List<CommentVO> list = commentService.getAllComment(aid);
        return AjaxResult.success(list);
    }
}
